package cn.edu.jxau.core.service;

import cn.edu.jxau.core.exception.ServiceException;
import cn.edu.jxau.core.util.DateUtils;
import cn.edu.jxau.core.util.StringUtil;
import cn.edu.jxau.framework.dao.core.Session;
import cn.edu.jxau.framework.dao.core.sqlSessionFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

/**
 * 检验线业务，国际标准业务
 * @author 巫发萍
 * spectrum3
 * 2017年8月23日
 */
public class ConnectionAlgorithmService extends ServiceSupport {
	// 日志信息
	private Logger logger = LoggerFactory.getLogger(ConnectionAlgorithmService.class);
	public ConnectionAlgorithmService(){
	}
	
	public ConnectionAlgorithmService(String view, Map<String, Object[]> params, Map<String, Object> data) throws ServiceException{
		/**
         * view service.xml中的name和视图对应
         * params request入口的参数数组
         * data 返回给Servlet的出口参数
         */
        super(view, params, data);
        execute(view, params, data); // 执行业务
	}
	
	/**
	 * 公开检验线
	 * @author 巫发萍
	 * @param params：存储边界类的数据
	 * @param data：出口参数，回送至web层
	 * @return 执行情况，和service.xml的result节点的name属性对应，代表转发页面
	 */
	@SuppressWarnings("unused")
	private void openConnectionAlgorithm (Map<String, Object[]> params, Map<String, Object> data){
		
	}
	/**
	 * 显示所有检验线
	 * @param params
	 * @param data
	 */
	@SuppressWarnings("unused")
	private void displayConnection (Map<String, Object[]> params, Map<String, Object> data){
		getConnectionAlgorithm(params, data);
				
		data.put("result", "success");
	}
	/**
	 * 查询检验线，将检测内容、被检测物、光盘类型、硬件类型组合好
	 * @author 巫发萍
	 * @param params：存储边界类的数据
	 * @param data：出口参数，回送至web层
	 * @return 执行情况，和service.xml的result节点的name属性对应，代表转发页面
	 */
	@SuppressWarnings("unused")
	private void getConnectionAlgorithm (Map<String, Object[]> params, Map<String, Object> data){
		String userID=getParamStringValue(params, "userID", 0);//得到userID
		
		Map<String, Object> param = new HashMap<String, Object>();    //封装传递给数据库的参数，用于算法查询
        List<HashMap<String, Object>> datas = new ArrayList<>();    //接收数据库返回回来的 用于算法查询
        
        param.put("userID", userID);
        
	    try {
			Session session = sqlSessionFactory.getInstance().getSession();
			session.execute("queryAllConnection", param, datas);
			
			if(datas.isEmpty()){
				return;
			}
			//遍历检验线，根据检验线编号将所有的被检测物和检测内容和光谱类型和硬件类型封装到每一个检验线
			for(HashMap<String, Object> d:datas){
				
				int state=(int)d.get("connectionAlgorithmState");
				if(state==0){
					d.replace("connectionAlgorithmState", "未公开");
				}else if(state==1){
					d.replace("connectionAlgorithmState", "公开");
				}else if(state==2){
					
					d.replace("connectionAlgorithmState", "待审核");
				}
				
				int id = Integer.parseInt(d.get("id")+"");//拿到检验线编号
				param.put("id",id );
				
				List<HashMap<String, Object>> detected = new ArrayList<>(); //用来接收数据库传回来的被测物
				session.execute("queryDetectedByID", param, detected);
				if(detected.isEmpty()){
				    continue;
				}
				d.put("detected", detected.get(0));//将被检测物内容封装到datas里(只有单行记录)
				
				
				int dtectedID=Integer.parseInt(detected.get(0).get("id")+"");//得到检验线被检测物id
				param.put("dtectedID", dtectedID);
				
				List<HashMap<String, Object>> content = new ArrayList<>(); //用来接收数据库传回来的检测物
				session.execute("queryContentByID", param, content);
				
				if(content.isEmpty()){
				    continue;
				}
				
				d.put("content", content);//将检测内容封装到datas里
				
				
				param.put("hardwareID", d.get("hardwareID"));
				List<HashMap<String, Object>> hardware = new ArrayList<>(); //用来接收数据库传回来的检测物
				session.execute("querySpectrumByHard", param, hardware);
				
				if(hardware.isEmpty()){
				    continue;
				}
				
				d.put("hardware", hardware.get(0));//将硬件和光谱类型封装到datas里(只有一行记录)	
				
			}
			
			data.put("datas", datas);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
	
	
	/**
	 * 删除检验线
	 * @author 巫发萍
	 * @param params：存储边界类的数据
	 * @param data：出口参数，回送至web层
	 * @return 执行情况，和service.xml的result节点的name属性对应，代表转发页面
	 */
	@SuppressWarnings("unused")
	private void deleteConnection(Map<String, Object[]> params, Map<String, Object> data){
		int id=Integer.parseInt(getParamStringValue(params, "id", 0));
		
		Map<String, Object> param = new HashMap<String, Object>();    //封装传递给数据库的参数，用于算法查询
        List<HashMap<String, Object>> datas = new ArrayList<>();    //接收数据库返回回来的 用于算法查询
        param.put("id", id);
        param.put("state", 3);//表示假删除
        Session session;
		try {
			session = sqlSessionFactory.getInstance().getSession();
			session.execute("deleteConnection", param, datas);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		data.put("result", "success");
	}
	
	/**
	 * 修改检验线
	 * @author 巫发萍
	 * @param params：存储边界类的数据
	 * @param data：出口参数，回送至web层
	 * @return 执行情况，和service.xml的result节点的name属性对应，代表转发页面
	 */
	@SuppressWarnings("unused")
	private void updateConnectionAlgorithm(Map<String, Object[]> params, Map<String, Object> data){
		Map<String, Object> param = new HashMap<String, Object>();    //封装传递给数据库的参数
		List<HashMap<String, Object>> datasConnectionAlgorithm = new ArrayList<>();    //接收数据库返回回来的 用于检验线表查询
		param.put("userID", getParamStringValue(params, "userID", 0));
        param.put("id", getParamStringValue(params, "id", 0));
        param.put("connectionAlgorithmName", getParamStringValue(params, "connectionAlgorithmName", 0));
        param.put("Hardware", getParamStringValue(params, "Hardware", 0));
        param.put("PretreatmentAlgorithm", getParamStringValue(params, "PretreatmentAlgorithm", 0));
        param.put("AnalysisAlgorithm", getParamStringValue(params, "AnalysisAlgorithm", 0));
        param.put("standard", getParamStringValue(params, "standard", 0));
        param.put("connectionAlgorithmDescribe", getParamStringValue(params, "connectionAlgorithmDescribe", 0));
        
        Session session =null;
        try {
			session=sqlSessionFactory.getInstance().getSession();
			session.execute("updateConnectionAlgorithm", param, datasConnectionAlgorithm);
			data.put("result", SUCCESS);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			session.releaseConnection();
		}
        
		
	}

	/**
	 * 查询检验线详细信息详细信息
	 *@author 巫发萍
	 * @param params
	 * @param data
	 */
	@SuppressWarnings("unused")
	private void getConnectionAlgorithmByID(Map<String, Object[]> params, Map<String, Object> data){
		Map<String, Object> param = new HashMap<String, Object>();    //封装传递给数据库的参数
		Map<String, Object> param1 = new HashMap<String, Object>();    //封装传递给数据库的参数
		Map<String, Object> param2 = new HashMap<String, Object>();    //封装传递给数据库的参数
        List<HashMap<String, Object>> datasConnectionAlgorithm = new ArrayList<>();    //接收数据库返回回来的 用于检验线表查询
        List<HashMap<String, Object>> datasDetecte = new ArrayList<>();    //接收数据库返回回来的 用于检验线-检测内容表
        List<HashMap<String, Object>> datasDetected = new ArrayList<>();    //接收数据库返回回来的 用于检测线-被检测物表
        
        param.put("userID", getParamStringValue(params, "userID", 0));
        param.put("id", getParamStringValue(params, "id", 0));
        Session session = null;
        try {
        	//通过检验线id取检验线
			session=sqlSessionFactory.getInstance().getSession();
			session.execute("getConnectionByID", param, datasConnectionAlgorithm);
			data.put("datasConnectionAlgorithm", datasConnectionAlgorithm);
			//通过检验线id取该检验线的被检测物
			param1.put("id", datasConnectionAlgorithm.get(0).get("id"));
			session.execute("queryDetectedByID", param1, datasDetected);
			data.put("datasDetected", datasDetected);
			
			//通过被检测物id取该检验线的检测内容
			for(int i=0;i<datasDetected.size();i++){
				param2.put("dtectedID", datasDetected.get(i).get("id"));
				session.execute("queryContentByID", param2, datasDetecte);				
			}
			data.put("datasDetecte", datasDetecte);
			data.put("result", SUCCESS);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			session.releaseConnection();
		}
	}
	
	/**
	 * 添加检验线
	 * @author 巫发萍
	 * @param params：存储边界类的数据
	 * @param data：出口参数，回送至web层
	 * @return 执行情况，和service.xml的result节点的name属性对应，代表转发页面
	 */
	@SuppressWarnings({ "unused", "unchecked" })
	private void addConnectionAlgorithm(Map<String, Object[]> params, Map<String, Object> data){
		Map<String, Object> paramConnectionAlgorithm = new HashMap<String, Object>();    //封装传递给数据库的参数
		Map<String, Object> paramDetected = new HashMap<String, Object>();    //封装传递给数据库的参数
		Map<String, Object> paramDetecte = new HashMap<String, Object>();    //封装传递给数据库的参数
        
        
        for(String key : params.keySet()){
        	System.out.println("key="+key+"***** value="+params.get(key));
        }
        
        paramConnectionAlgorithm.put("connectionAlgorithmID", "20151712");
        paramConnectionAlgorithm.put("hardwareID", getParamStringValue(params, "hardwareID", 0));
        paramConnectionAlgorithm.put("connectionAlgorithmName", getParamStringValue(params, "connectionAlgorithmName", 0));
        paramConnectionAlgorithm.put("analysisAlgorithmID", getParamStringValue(params, "analysisAlgorithmID", 0));
        paramConnectionAlgorithm.put("PretreatmentAlgorithmID", getParamStringValue(params, "PretreatmentAlgorithmID", 0));
        paramConnectionAlgorithm.put("standardID", getParamStringValue(params, "standardID", 0));
        paramConnectionAlgorithm.put("connectionAlgorithmState", 0);
        paramConnectionAlgorithm.put("connectionAlgorithmDescribe", getParamStringValue(params, "connectionAlgorithmDescribe", 0));
        paramConnectionAlgorithm.put("connectionAlgorithmSaveTime", DateUtils.getNowTime());
        paramConnectionAlgorithm.put("userID", getParamStringValue(params, "userID", 0));
        
        int length = Integer.parseInt(getParamStringValue(params, "Detected_DetectesLength", 0));
        List<String> Detected = new ArrayList<>();//存放被检测物
        for(int i=0;i<length;i++){
        	String key1 = "Detected_Detectes["+i+"][Detected]";
        	Detected.add(getParamStringValue(params, key1, 0));
        	
        }

        List<ArrayList<String>> Detecte = new ArrayList<>();//存放检测内容
        for(int j=0;j<length;j++){
        	String key2 = "Detected_Detectes["+j+"][Detecte][]";
        	ArrayList<String> detecte1 = new ArrayList<>();
	        for(int i=0;i<params.get(key2).length;i++){
	        	detecte1.add(getParamStringValue(params, key2, i));
	        }
	        Detecte.add(detecte1);
        }

        Session session = null;
        try {
        	List<HashMap<String, Object>> datas = new ArrayList<>();    //接收数据库返回回来的 
			session = sqlSessionFactory.getInstance().getSession();
			Boolean aa = session.execute("addConnection", paramConnectionAlgorithm, datas);
			
			for(int i=0;i<Detected.size();i++){
				List<HashMap<String, Object>> datas1 = new ArrayList<>();    //接收数据库返回回来的 
				paramDetected.put("detectedID", Detected.get(i));
				paramDetected.put("connectionAlgorithmID", datas.get(0).get("primary"));
				Boolean bb = session.execute("addConnectionDetected", paramDetected, datas1);
				
				for(int j=0;j<Detecte.get(i).size();j++){
					paramDetecte.put("connectionAlgorithmeDtectedID", datas1.get(0).get("primary"));
					paramDetecte.put("connectionAlgorithmeDtecteID", Detecte.get(i).get(j));
					Boolean cc = session.execute("addConnectionDetecte", paramDetecte, datas1);
				}
				
			}
			data.put("result", SUCCESS);
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			session.releaseConnection();
		}
        
        
	}	
	
	/**
	 * 添加检验线时查询信息
	 *@author 巫发萍
	 * @param params
	 * @param data
	 */
	@SuppressWarnings("unchecked")
	private void getConnectionAlgorithmInfo(Map<String, Object[]> params, Map<String, Object> data){
		Map<String, Object> param = new HashMap<String, Object>();    //封装传递给数据库的参数
        List<HashMap<String, Object>> datasHardware = new ArrayList<>();    //接收数据库返回回来的 用于硬件查询
        List<HashMap<String, Object>> datasAlgorithm = new ArrayList<>();    //接收数据库返回回来的 用于算法查询
        List<HashMap<String, Object>> datasDetecte = new ArrayList<>();    //接收数据库返回回来的 用于检测内容查询
        List<HashMap<String, Object>> datasDetecteD = new ArrayList<>();    //接收数据库返回回来的 用于被检测物查询
        List<HashMap<String, Object>> datasStandard = new ArrayList<>();    //接收数据库返回回来的 用于标准查询
        
        Session session = null;
        
        try {
			session = sqlSessionFactory.getInstance().getSession();
			session.execute("getHardware", params, datasHardware);
			session.execute("getAlgorithm", params, datasAlgorithm);
			session.execute("getDetecte", params, datasDetecte);
			session.execute("getDetecteD", params, datasDetecteD);
			session.execute("getStandard", params, datasStandard);
			
			data.put("datasHardware", datasHardware);
			data.put("datasAlgorithm", datasAlgorithm);
			data.put("datasDetecte", datasDetecte);
			data.put("datasDetecteD", datasDetecteD);
			data.put("datasStandard", datasStandard);
			data.put("result", SUCCESS);
			
			
		} catch (ClassNotFoundException e) {
		} catch (DocumentException e) {
		}finally {
			session.releaseConnection();
		}
	}
	
	/**
	 * 公开检验线
	 * @param params
	 * @param data
	 */
	@SuppressWarnings("unused")
	private void openConnection(Map<String, Object[]> params, Map<String, Object> data){
		int id=Integer.parseInt(getParamStringValue(params, "id", 0));
		
		Map<String, Object> param = new HashMap<String, Object>();    //封装传递给数据库的参数，用于算法查询
        List<HashMap<String, Object>> datas = new ArrayList<>();    //接收数据库返回回来的 用于算法查询
        param.put("id", id);
        param.put("state", 2);//1表示待审核
        Session session;
        try {
			session = sqlSessionFactory.getInstance().getSession();
			session.execute("openConnection", param, datas);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
        data.put("result", "success");
	}	

	/**
	 * 管理员查看所有已公开的检验线信息
	 * @zclong
	 * @2017年9月22日
	 * @ReturnType: void
	 * @param params
	 * @param data
	 */
	@SuppressWarnings({ "unused", "unchecked" })
    private void adminDisplayConnection (Map<String, Object[]> params, Map<String, Object> data){
	    List<HashMap<String, Object>> datas = new ArrayList<>();    //接收数据库返回回来的
	    Map<String, Object> param = new HashMap<String, Object>();    //封装传递给数据库的参数
	    param.put("connectionAlgorithmState", 1); // connectionAlgorithmState为1表示已公开
	    Session session;
        try {
            session = sqlSessionFactory.getInstance().getSession();
            session.execute("adminDisplayConnection", param, datas);
            if(datas != null) {
                data.put("connectionList", datas);
                data.put("result", "success");
                return;
            }else {
                data.put("error_msg", "没有检验线信息！");
                data.put("result", "failed");
                return;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }         
    }
	
	/**
	 * 查询检验线详细信息详细信息
	 * @zclong
	 * @2017年9月23日
	 * @ReturnType: void
	 * @param params
	 * @param data
	 */
    @SuppressWarnings("unused")
    private void connectionAlgorithmInfo(Map<String, Object[]> params, Map<String, Object> data){
        Map<String, Object> param = new HashMap<String, Object>();    //封装传递给数据库的参数
        Map<String, Object> param1 = new HashMap<String, Object>();    //封装传递给数据库的参数
        Map<String, Object> param2 = new HashMap<String, Object>();    //封装传递给数据库的参数
        List<HashMap<String, Object>> datasConnectionAlgorithm = new ArrayList<>();    //接收数据库返回回来的 用于检验线表查询
        List<HashMap<String, Object>> datasDetecte = new ArrayList<>();    //接收数据库返回回来的 用于检验线-检测内容表
        List<HashMap<String, Object>> datasDetected = new ArrayList<>();    //接收数据库返回回来的 用于检测线-被检测物表
        
        param.put("userID", getParamStringValue(params, "userid", 0));
        param.put("id", getParamStringValue(params, "id", 0));
        Session session = null;
        try {
            //通过检验线id取检验线
            session=sqlSessionFactory.getInstance().getSession();
            session.execute("getConnectionByID", param, datasConnectionAlgorithm);
            data.put("datasConnectionAlgorithm", datasConnectionAlgorithm);
            //通过检验线id取该检验线的被检测物
            param1.put("id", datasConnectionAlgorithm.get(0).get("id"));
            session.execute("queryDetectedByID", param1, datasDetected);
            data.put("datasDetected", datasDetected);
            
            //通过被检测物id取该检验线的检测内容
            for(int i=0;i<datasDetected.size();i++){
                param2.put("dtectedID", datasDetected.get(i).get("id"));
                session.execute("queryContentByID", param2, datasDetecte);              
            }
            data.put("datasDetecte", datasDetecte);
            data.put("result", SUCCESS);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            session.releaseConnection();
        }
    }
    
    /**
     * 管理员查看所有标准信息
     * @zclong
     * @2017年9月23日
     * @ReturnType: void
     * @param params
     * @param data
     */
    @SuppressWarnings("unused")
    private void listStandard(Map<String, Object[]> params, Map<String, Object> data){
        Map<String, Object> param = new HashMap<String, Object>();    //封装传递给数据库的参数
        List<HashMap<String, Object>> datas = new ArrayList<>();    //封装传递给数据库的参数
        Session session = null;
        try {
            //通过检验线id取检验线
            session=sqlSessionFactory.getInstance().getSession();
            session.execute("listStandard", param, datas);
            data.put("listStandards", datas);
            data.put("result", SUCCESS);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            session.releaseConnection();
        }
    }
    
    /**
     * 管理员修改标准信息
     * @zclong
     * @2017年9月23日
     * @ReturnType: void
     * @param params
     * @param data
     */
    @SuppressWarnings("unused")
    private void updateStandard(Map<String, Object[]> params, Map<String, Object> data){
        Map<String, Object> param = new HashMap<String, Object>();    //封装传递给数据库的参数
        List<HashMap<String, Object>> datas = new ArrayList<>();    //封装传递给数据库的参数
        
        int id = Integer.parseInt(getParamStringValue(params, "id", 0));
        String standardName = getParamStringValue(params, "standardName", 0);
        if(StringUtil.isAnyBlank(standardName)) {
            data.put("error_msg", "信息错误");
            data.put("result", FAILED);
            return;
        }
        Session session = null;
        param.put("id", id);
        param.put("standardName", standardName);
        try {
            //通过检验线id取检验线
            session=sqlSessionFactory.getInstance().getSession();
            boolean flag = session.execute("updateStandard", param, datas);
            if(false == flag) {
                data.put("error_msg", "信息错误");
                data.put("result", FAILED);
                return;
            }
            data.put("result", SUCCESS);
            return;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.releaseConnection();
        }
    }
    
    /**
     * 管理员添加标准信息
     * @zclong
     * @2017年9月23日
     * @ReturnType: void
     * @param params
     * @param data
     */
    @SuppressWarnings("unused")
    private void addStandard(Map<String, Object[]> params, Map<String, Object> data){
        Map<String, Object> param = new HashMap<String, Object>();    //封装传递给数据库的参数
        List<HashMap<String, Object>> datas = new ArrayList<>();    //封装传递给数据库的参数
        
        String standardName = getParamStringValue(params, "standardName", 0);
        if(StringUtil.isAnyBlank(standardName)) {
            data.put("error_msg", "信息错误");
            data.put("result", FAILED);
            return;
        }
        Session session = null;
        param.put("standardName", standardName);
        try {
            //通过检验线id取检验线
            session=sqlSessionFactory.getInstance().getSession();
            boolean flag = session.execute("addStandard", param, datas);
            if(false == flag) {
                data.put("error_msg", "信息错误");
                data.put("result", FAILED);
                return;
            }
            data.put("result", SUCCESS);
            return;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.releaseConnection();
        }
    }
}
